<template>
    <div class="my-main">
          <div class="my-list">
              <div class="my-separator">
                  <el-breadcrumb class="my-item" separator-class="el-icon-arrow-right">
                      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
                      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
                    </el-breadcrumb>
                      <template class="search" style="margin-top: 15px;">
                        <el-button type="primary" @click="roleInfoDialog=true">添加角色</el-button>
                      </template>
                </div>
                <el-main>
                  <el-table  
                  :data="rolesData" 
                  style="width: 100%" 
                  border 
                  class="tableBox"
                  ref="tableBox"
                  @expand-change="expandChangeFn"
                  >
                      <el-table-column type="expand">
                        <template  #default="scope">
                          <template v-if="scope.row.children.length>0">
                              <el-row v-for="item1 in scope.row.children" :key="item1.id">
                                <el-col :span="4">
                                  <el-tag closable @close="deletePowerFn(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                </el-col>
                                <el-col :span="20">
                                    <el-row v-for="item2 in item1.children" :key="item2.id">
                                      <el-col :span="6">
                                        <el-tag closable type="success" @close="deletePowerFn(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                      </el-col>
                                      <el-col :span="18">
                                        <el-tag type="warning" closable v-for="item3 in item2.children" :key="item3.id" @close="deletePowerFn(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                      </el-col>
                                    </el-row>
                                </el-col>
                              </el-row>
                          </template>
                              <el-row v-else>
                                暂无权限
                              </el-row>
                        </template>
                      </el-table-column>
                      <el-table-column type="index" label="#"></el-table-column>
                      <el-table-column prop="roleName" label="角色名称" width="350"></el-table-column>
                      <el-table-column prop="roleDesc" label="角色描述" width="350"></el-table-column>
                    <el-table-column  label="操作" width="450">
                      <template #default="scope">
                           <el-row >
                              <el-button type="primary" icon="el-icon-edit" circle @click="RoleDialog(scope.row)"></el-button>
                              <el-button type="danger" icon="el-icon-delete" circle @click="deleteRoleFn(scope.row.id)"></el-button>
                              <el-button type="success" icon="el-icon-check" circle @click="getRolesFn(scope.row)"></el-button>
                            </el-row>
                      </template>
                     
                    </el-table-column>
                  </el-table>
                </el-main>
                    <!-- 新增角色的弹框 -->
                 <el-dialog title="新增角色" v-model="roleInfoDialog" >
                  <el-form :model="roleInfoForm" :rules="rules" ref="roleInfoFormly">
                    <el-form-item label="角色名" prop='roleName'>
                      <el-input v-model="roleInfoForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop='roleDesc' >
                      <el-input v-model="roleInfoForm.roleDesc" autocomplete="off"></el-input>
                    </el-form-item>
                  </el-form>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="roleInfoDialog = false">取 消</el-button>
                      <el-button type="primary" @click="addRolesFn()">确 定</el-button>
                    </span>
                  </template>
                </el-dialog>
                   <!-- 编辑角色的弹框 -->
                <el-dialog title="编辑角色" v-model="editRoleInfoDialog">
                  <el-form :model="editRoleInfoForm">
                    <el-form-item label="用户id" :label-width="formLabelWidth"
                    prop="id"
                    >
                      <el-input v-model="editRoleInfoForm.id" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="角色名" :label-width="formLabelWidth"
                    prop="roleName"
                    >
                      <el-input v-model="editRoleInfoForm.roleName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" :label-width="formLabelWidth"
                     prop="roleDesc"
                    >
                      <el-input v-model="editRoleInfoForm.roleDesc" autocomplete="off"></el-input>
                    </el-form-item>
                  </el-form>
                  <div class="dialog-footer">
                    <el-button @click="editRoleInfoDialog = false">取 消</el-button>
                    <el-button type="primary" @click="editRoleFn()">确 定</el-button>
                  </div>
                </el-dialog>

                 <!-- 角色授权的弹框 -->
                 <el-dialog title="角色授权" v-model="RoleEmpowerInfoDialog" @closed="handleClose">
                  <el-form>
                    <el-tree
                     :data="arrData.roleList"
                      show-checkbox
                      node-key="id"
                      ref="tree"
                      highlight-current
                      :default-expanded-keys="arrData.defaultExpandKeys"
                      :default-checked-keys="arrData.defaultExpandKeys"
                      :props="defaultProps"
                      >
                    </el-tree>
                  </el-form>
                  <template #footer>
                  <span class="dialog-footer">
                    <el-button type="primary" @click="empowerRoleFn">提交</el-button>
                  </span>
                  </template>
                </el-dialog>
            </div>
        </div>
</template>

<script>
import {addRoles, getRoles,exidRoles,delectRoles,delectRolesRightS,getRights,setRolesRights} from "../../http/api"
import {onMounted, getCurrentInstance, reactive,ref,nextTick} from "vue";
import { ElMessageBox, ElMessage } from 'element-plus'
export default {
  name: 'Home',
  setup(){
    const { proxy } = getCurrentInstance();
    const rolesData=reactive([])
    const roleInfoDialog=ref(false)
    const roleInfoFormly=ref()
    const tableBox=ref()
    const roleInfoForm=reactive({
      roleName:'',
      roleDesc:''
    })
    const rules=reactive({
       roleName: [{required:true, message:'请输入角色名', trigger: 'blur' }],
        roleDesc: [{required:true, message:'请输入角色描述', trigger: 'blur' }]
    })
    const editRoleInfoDialog=ref(false)
    const editRoleInfoForm=reactive({
        id:'',
        roleName:'',
        roleDesc:''
    })
    const RoleEmpowerInfoDialog=ref(false)
    // const roleList=reactive([])
    const arrData=reactive({
      arr:[],
      roleList:[],
      defaultExpandKeys:[],
      roleId:""

    })
    const defaultProps=reactive({
        children: 'children',
        label: 'authName'
    })
   
    // const =ref()
   

    // 获取角色列表
    const  getRolesly = () =>{
       getRoles('list').then(res=>{
            console.log(res)
            Object.assign(rolesData,res)
          })
    } 

    onMounted(()=>{
     getRolesly()
    })
    // 添加角色
    const addRolesFn = () =>{
      console.log(111)
      proxy.$refs.roleInfoFormly.validate(async valid =>{
        if(valid){
          await addRoles(roleInfoForm);
          console.log(roleInfoForm)
          roleInfoDialog.value=false;
          proxy.$refs.roleInfoFormly.resetFields();
          getRolesly()
        }
      })
    }

    // 编辑角色的消息弹框  回显信息
      const  RoleDialog = (row) => {
        console.log('row',row);
        editRoleInfoDialog.value=true;
        editRoleInfoForm.id=row.id
        editRoleInfoForm.roleName=row.roleName
        editRoleInfoForm.roleDesc=row.roleDesc
      }
    // 编辑提交
     const editRoleFn  = async() =>{
        const {id,roleName,roleDesc} = editRoleInfoForm
        console.log("@@@",editRoleInfoForm)
        await exidRoles(id,{roleName,roleDesc});
        editRoleInfoDialog.value=false;
        getRolesly()
      }
    // 删除角色
     const  deleteRoleFn = (id) =>{
        ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await delectRoles(id);
          getRolesly()
          console.log(43243243)
        }).catch(() => {
           ElMessage({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
      // 获取权限列表
      const getRolesFn = async (obj) => {
        // console.log("------->",proxy)
        const res = await getRights('tree')
        arrData.roleList=res;
        arrData.roleId=obj.id
        RoleEmpowerInfoDialog.value=true;
        // console.log('====>',obj)
        // deepArr(obj.children)
        nextTick(()=>{
          // console.log("////",arr)
          deepArr(obj.children)
          console.log("####",proxy.$refs.tree)
          proxy.$refs.tree.setCheckedNodes(arrData.arr);
         arrData.defaultExpandKeys=proxy.$refs.tree.getCheckedKeys();
        })
      }

      //  删除角色授权
      const deletePowerFn = async (scopeRow,rightId) =>{
        const res=await delectRolesRightS(scopeRow.id,rightId);
        Object.assign(scopeRow.children,res)
      }

      const deepArr = (array) => {
        for(let i in array){
          let data=array[i];
          if(data.children){
           return deepArr(data.children)
          }else{
           arrData.arr.push(data);
          }
        }
      } 

      const handleClose = () => {
        console.log("$$$")

        arrData.defaultExpandKeys=[];
        arrData.roleList=[];
        arrData.arr=[]
      }

      // 角色授权
      const empowerRoleFn = async() =>{
        let list=[];
        let nodes=proxy.$refs.tree.getCheckedNodes(false,true);
        console.log("######",nodes)
        nodes.map(item=>{
          list.push(item.id)
        })
        // const arrId=arrData.roleId
        // const arrList=list.join(',')
        // console.log(arrId,arrList)
       const res= await setRolesRights(arrData.roleId,{rids:list.join(',')})
       arrData.defaultExpandKeys=res
        console.log("aaaa")
        RoleEmpowerInfoDialog.value=false;
        getRolesly();
      }
       // 开启下一个之后，上一个关闭
      const expandChangeFn = (row,expandedRows ) =>{
        console.log("====>",row,expandedRows)
        if(expandedRows.length>1){
          proxy.$refs.tableBox.toggleRowExpansion(expandedRows[0],false);
        }
      }

    return {rolesData,addRolesFn,tableBox,roleInfoDialog,roleInfoForm,rules,roleInfoFormly,getRolesly,editRoleInfoDialog,
    editRoleInfoForm,RoleDialog,editRoleFn,deleteRoleFn,deletePowerFn,getRolesFn,RoleEmpowerInfoDialog,defaultProps,
    handleClose,empowerRoleFn,expandChangeFn,arrData}
  }
}
</script>

<style scoped>
.my-item{
  padding: 5px 0px;
}
.search{
  display: flex;
  align-items: flex-start;
}
.my-main{
  background-color: #eee;
  display: block;
  flex: 1;
  flex-basis: auto;
  /* overflow: auto; */
  padding: 10px;
}
.my-inp{
  width: 250px;
  margin-right: 20px;
}
.my-list{
  background-color: #fff;
}
.el-main{
  padding: 15px;
  border-color: #fff;
  border-radius: 5px;
  height: calc(100vh - 160px);
  box-sizing: border-box;
  /* overflow-x: auto; */
}
.el-tag{
  margin: 8px;
}
.tableBox ::v-deep .el-table__expanded-cell{
  padding: 16px 40px;
}
.el-table--scrollable-x .el-table__body-wrapper{
  overflow-x:hidden  !important;
}
</style>